<?php
/**
 * 评论
 * User: Administrator
 * Date: 2022/3/15
 * Time: 9:47
 */

namespace app\api\controller;
use think\Request;
use app\common\controller\Api;
use think\Db;

class Comment extends Api
{
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['list'];
    protected $noNeedRight = '*';

    public function list()
    {
        if (!Request::instance()->isGet())
            $this->error('请求方式不正确');
        $page = input('post.page',1);
        $limit = input('post.limit',10);
        $list = Db::name('comment')->alias('a')
                ->join('user b','a.user_id=b.id')
                ->join('success_case c','a.success_case_id=c.id')
                ->where('a.pid',0)
                ->field('a.*,b.nickname,b.avatar,c.title as success_title,FROM_UNIXTIME(a.createtime,"%Y-%m-%d")as time')
                ->paginate($limit,false,['page'=>$page]);


        if($list)
        {
            $list = $list->toArray();
            foreach ($list['data'] as $k=>&$v)
            {
                $v['avatar'] = $v['avatar'] ? cdnurl($v['avatar'], true) : letter_avatar($v['nickname']);
                $sonList = Db::name('comment')->alias('a')
                    ->join('user b','a.user_id=b.id')
                    ->join('success_case c','a.success_case_id=c.id')
                    ->where('pid',$v['id'])
                    ->field('a.*,b.nickname,b.avatar,c.title as success_title,FROM_UNIXTIME(a.createtime,"%Y-%m-%d")as time')
                    ->select();
                if($sonList)
                {
                    foreach ($sonList as $key=>&$value)
                    {
                        $value['avatar'] = $value['avatar'] ? cdnurl($value['avatar'], true) : letter_avatar($value['nickname']);
                    }
                }
                $v['son'] = $sonList;
            }
            $this->success('',$list);
        }

        $this->error('暂无数据');
    }

    public function add()
    {
        if (!Request::instance()->isPost())
            $this->error('请求方式不正确');

        $params = input('post.');
        $result = $this->validate($params,'Comment');

        if (true !== $result) {
            // 验证失败 输出错误信息
            $this->error($result);
        }
        $user_id = $this->auth->id;
        $params['user_id'] = $user_id;
        $params['createtime'] = time();
        $params['updatetime'] = time();
        $res = Db::name('comment')->insert($params);
        if($res)
            $this->success('发布成功');
        $this->error('发布失败');
    }
}